package com.ruoyi.project.wenyanwen.generate.convert;

import com.ruoyi.common.utils.AESUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public abstract class AbstractConvert implements Convert {

    public static final Logger log = LoggerFactory.getLogger(AbstractConvert.class);

    static String key = "13f439726d2d4522";

    public static byte[] zipAndencrypt(String s) {

        if (StringUtils.isEmpty(s)) {
            return new byte[0];
        }

        try {
            AESUtil util = new AESUtil(key.getBytes());
            byte[] source = s.getBytes("UTF8");
            byte[] zipBytes = zip(source);
            byte[] encryptBytes = util.encrypt(zipBytes);
            log.info("source[{}], zip[{}], encrypt[{}]", source.length, zipBytes.length, encryptBytes.length);
            return encryptBytes;
        } catch (Exception e) {
            log.error("加密出错");
            log.error(e.getMessage(), e);
            return new byte[0];
        }
    }

    public static byte[] zipAndencrypt(byte[] bytes) {

        try {
            AESUtil util = new AESUtil(key.getBytes());
            byte[] zipBytes = zip(bytes);
            byte[] encryptBytes = util.encrypt(zipBytes);
            log.info("source[{}], zip[{}], encrypt[{}]", bytes.length, zipBytes.length, encryptBytes.length);
            return encryptBytes;
        } catch (Exception e) {
            log.error("加密出错");
            log.error(e.getMessage(), e);
            return new byte[0];
        }
    }

    public static byte[] encrypt(String s) {

        if (StringUtils.isEmpty(s)) {
            return new byte[0];
        }

        try {
            AESUtil util = new AESUtil(key.getBytes());
            byte[] source = s.getBytes("UTF8");
            byte[] encryptBytes = util.encrypt(source);
            log.info("source[{}], encrypt[{}]", source.length, encryptBytes.length);
            return encryptBytes;
        } catch (Exception e) {
            log.error("加密出错");
            log.error(e.getMessage(), e);
            return new byte[0];
        }
    }

    /**
     * zip压缩
     *
     * @param bytes
     * @return
     */
    public static byte[] zip(byte[] bytes) {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = null;
        byte[] result = new byte[0];
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(bytes);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(gzip);
        }

        return out.toByteArray();
    }


}
